<template>
  <view class="editor-container">
    <!-- 工具栏 -->
    <view class="toolbar">
      <view class="toolbar-left">
        <view class="upload-btn" @click="handleImageUpload">
          <uni-icons type="image" size="20" color="#2775b6"></uni-icons>
          <text class="btn-text">图片</text>
        </view>
        <view class="delete-btn" @click="handleDelete" v-if="showDelete">
          <uni-icons type="trash" size="20" color="#ff4d4f"></uni-icons>
          <text class="btn-text">删除</text>
        </view>
      </view>
      <view class="toolbar-right">
        <text class="word-count">{{ wordCount }}字</text>
        <view class="save-btn" @click="handleSave">
          <text class="save-text">保存</text>
        </view>
      </view>
    </view>

    <!-- 编辑区域 -->
    <scroll-view 
      class="editor-scroll"
      scroll-y
      :style="{ height: scrollHeight + 'rpx' }"
    >
      <textarea
        class="text-area"
        v-model="content"
        placeholder="记录你的今日点滴..."
        placeholder-class="placeholder"
        :show-confirm-bar="false"
        maxlength="-1"
      ></textarea>
    </scroll-view>

    <!-- 图片预览 -->
    <scroll-view class="image-preview" scroll-x v-if="images && images.length > 0">
      <view v-for="(img, index) in images" :key="index" class="image-wrapper">
        <image 
          :src="processImagePath(img)"
          class="preview-image"
          mode="aspectFill"
          @click="previewImage(index)"
        ></image>
        <view class="delete-icon" @click="removeImage(index)">
          <uni-icons type="close" size="16" color="#fff"></uni-icons>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'  // 确保导入onMounted

const props = defineProps({
  diaryId: String,
  initialContent: {
    type: String,
    default: ''
  },
  initialImages: {
    type: Array,
    default: () => []
  },
  showDelete: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['save', 'delete', 'cancel'])

const content = ref(props.initialContent)
const images = ref(props.initialImages || [])  // 确保images初始化为数组
const isSaving = ref(false)
const scrollHeight = ref(300)

// 动态计算高度
onMounted(() => {
  calcScrollHeight()
})

const calcScrollHeight = () => {
  uni.getSystemInfo({
    success: (res) => {
      // 参数说明（单位px）：
      // 50 - 顶部安全区域预留
      // 60 - 工具栏高度
      // 100 - 图片预览区域高度（有图片时）
      const baseDeduction = 50 + 60
      const dynamicDeduction = images.value?.length > 0 ? 100 : 0
      
      // 最终计算（增加10px额外空间）
      scrollHeight.value = res.windowHeight - baseDeduction - dynamicDeduction + 10
      
      // 设置最小高度保证体验
      if (scrollHeight.value < 300) {
        scrollHeight.value = 300
      }
    }
  })
}

// 处理图片路径
const processImagePath = (img) => {
  return img?.startsWith('_www/') ? `/static/${img}` : img
}

// 字数统计
const wordCount = computed(() => {
  return content.value?.replace(/\s/g, '').length || 0
})

// 图片上传
const handleImageUpload = async () => {
  try {
    const res = await uni.chooseImage({
      count: 3 - (images.value?.length || 0),
      sizeType: ['compressed'],
      sourceType: ['album', 'camera']
    })
    images.value = [...(images.value || []), ...res.tempFilePaths]
    calcScrollHeight()
  } catch (error) {
    uni.showToast({ title: '最多添加3张图片', icon: 'none' })
  }
}

// 删除图片
const removeImage = (index) => {
  if (images.value) {
    images.value.splice(index, 1)
    calcScrollHeight()
  }
}

// 预览图片
const previewImage = (index) => {
  if (images.value) {
    uni.previewImage({
      current: index,
      urls: images.value.map(processImagePath)
    })
  }
}

// 保存处理
const handleSave = async () => {
  if (isSaving.value) return
  isSaving.value = true

  try {
    emit('save', {
      content: content.value,
      images: images.value || []
    })
  } catch (error) {
    uni.showToast({ title: '保存失败，请重试', icon: 'none' })
  } finally {
    isSaving.value = false
  }
}

// 删除处理
const handleDelete = () => {
  uni.showModal({
    title: '删除确认',
    content: '确定要删除这条日志吗？',
    success: (res) => {
      if (res.confirm) {
        emit('delete', props.diaryId)
      }
    }
  })
}

// 监听初始内容变化
watch(() => props.initialContent, (newVal) => {
  content.value = newVal
})

// 监听初始图片变化
watch(() => props.initialImages, (newVal) => {
  images.value = newVal || []
  calcScrollHeight()
}, { immediate: true })
</script>

<style scoped>
.editor-container {
  padding: 16px;
  background: #fff;
  border-radius: 16px 16px 0 0;
  display: flex;
  flex-direction: column;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 12px;
  border-bottom: 1px solid #eee;
}

.toolbar-left, .toolbar-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 恢复上传按钮样式 */
.upload-btn {
  display: flex;
  align-items: center;
  padding: 6px 12px;
  background: rgba(135, 206, 235, 0.1);
  border-radius: 6px;
  transition: all 0.2s;
}

.upload-btn:active {
  background: rgba(135, 206, 235, 0.2);
}

.btn-text {
  font-size: 14px;
  color: #2775b6;
  margin-left: 4px;
}

.delete-btn {
  display: flex;
  align-items: center;
  padding: 6px 12px;
  background: rgba(255, 77, 79, 0.1);
  border-radius: 6px;
  transition: all 0.2s;
}

.delete-btn:active {
  background: rgba(255, 77, 79, 0.2);
}

.word-count {
  font-size: 12px;
  color: #999;
}

.save-btn {
  padding: 8px 20px;
  background: #87CEEB;
  border-radius: 18px;
}

.save-text {
  color: #fff;
  font-size: 14px;
  font-weight: 500;
}

/* 新增滚动容器样式 */
.editor-scroll {
  width: 100%;
  border-bottom: 1px solid #eee;
}

.text-area {
  width: 100%;
  min-height: 800rpx;
  padding: 16px 0;
  font-size: 15px;
  line-height: 1.6;
  color: #333;
  /* 移除固定高度 */
  height: auto;
}

.placeholder {
  color: #ccc;
}

.image-preview {
  margin-top: 16px;
  white-space: nowrap;
}

.image-wrapper {
  position: relative;
  display: inline-block;
  width: 80px;
  height: 80px;
  margin-right: 8px;
  border-radius: 6px;
  overflow: hidden;
}

.preview-image {
  width: 100%;
  height: 100%;
}

.delete-icon {
  position: absolute;
  right: 4px;
  top: 4px;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>